<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Design extends Common
{
    public function designRender()
    {
        // 基础组件
        $componts = [
            'text_compont',
            'hidden_compont',
            'password_compont',
            'textarea_compont',
            'date_compont',
            'switch_compont',
            'select_compont',
            'select2_compont',
            'radio_compont',
            'checkbox_compont',
            'dateRange_compont',
            'editor_compont',
            'uploadImage_compont',
            'uploadImages_compont',
            'submitData_compont',
        ];

        foreach ($componts as $v) {
            $this->assign($v, $this->view->fetch('/design/componts/' . $v));
        }

        return $this->view->fetch();
    }

    public function designForm()
    {
        $this->assign('title', '自定义表单');
        return $this->view->fetch();
    }

    /**
     * 生成 新增/编辑/删除 php代码
     * */
    public function getDoCode()
    {
        $input = Request()->param();

        $table = $input['table'];
        $action = $input['action'];
        $title = $input['title'];
        $url = $input['url'];
        $json = json_decode($input['json'], true);

        if ($json) {
            // 参数
            $params = '';
            // 判断
            $judged = '';
            // 提交数据
            $form_data = '';
            foreach ($json as $k => $v) {
                // 参数
                if ($v['name'] || $v['startDateName'] || $v['endDateName']) {
                    if ($v['id'] == 'dateRange') {
                        $params .= ($k > 0 ? '        ' : '') . '$' . $v['startDateName'] . ' = $input["' . $v['startDateName'] . '"];' . (($k + 1 < count($json)) ? PHP_EOL : '');
                        $params .= ($k > 0 ? '        ' : '') . '$' . $v['endDateName'] . ' = $input["' . $v['endDateName'] . '"];' . (($k + 1 < count($json)) ? PHP_EOL : '');
                    } else {
                        $params .= ($k > 0 ? '        ' : '') . '$' . $v['name'] . ' = $input["' . $v['name'] . '"];' . (($k + 1 < count($json)) ? PHP_EOL : '');
                    }
                }

                // 判断
                if ($v['required'] === '0') {
                    $notice_type = '';
                    if (in_array($v['id'], ['text', 'password', 'textarea', 'editor'])) {
                        $notice_type = '请输入';
                    }
                    if (in_array($v['id'], ['date', 'dateRange', 'switch', 'select', 'checkbox', 'radio'])) {
                        $notice_type = '请选择';
                    }
                    if (in_array($v['id'], ['uploadImage', 'uploadImages'])) {
                        $notice_type = '请上传';
                    }
                    if ($v['id'] == 'dateRange') {
                        $judged .= ($k > 0 ? '        ' : '') . 'if (empty($' . $v['startDateName'] . ') && empty($' . $v['endDateName'] . ')) adminReturn(2, "' . $notice_type . $v['label'] . '");' . (($k + 1 < count($json)) ? PHP_EOL : '');
                    } else {
                        $judged .= ($k > 0 ? '        ' : '') . 'if (empty($' . $v['name'] . ')) adminReturn(2, "' . $notice_type . $v['label'] . '");' . (($k + 1 < count($json)) ? PHP_EOL : '');
                    }
                }

                // 提交数据
                if ($v['name'] || $v['startDateName'] || $v['endDateName']) {
                    if ($v['id'] == 'dateRange') {
                        $form_data .= ($k > 0 ? '            ' : '') . '"' . $v['startDateName'] . '" => $' . $v['startDateName'] . (($k + 1 < count($json)) ? ',' . PHP_EOL : '');
                        $form_data .= ($k > 0 ? '            ' : '') . '"' . $v['endDateName'] . '" => $' . $v['endDateName'] . (($k + 1 < count($json)) ? ',' . PHP_EOL : '');
                    } else {
                        $form_data .= ($k > 0 ? '            ' : '') . '"' . $v['name'] . '" => $' . $v['name'] . (($k + 1 < count($json)) ? ',' . PHP_EOL : '');
                    }
                }
            }

            $doAction = ucwords($action);

            $code = <<<AAA
/**
 * 新增/编辑 {$title}
 * */
public function do{$doAction}()
{
    if (Request()->isPost()) {
        \$input = Request()->param();

        \$id = \$input["id"];
        {$params}

        {$judged}
        
        \$data = [
            {$form_data}
        ];

        if (\$id > 0) {
            \$res = Db::name('{$table}')->where(['id' => \$id])->update(\$data);
            if (\$res) {
                adminReturn(1, '编辑{$title}成功', url('{$url}'));
            } else {
                adminReturn(2, '编辑{$title}失败或未编辑');
            }
        } else {
            \$res = Db::name('{$table}')->insert(\$data);
            if (\$res) {
                adminReturn(1, '新增{$title}成功', url('{$url}'));
            } else {
                adminReturn(2, '新增{$title}失败');
            }
        }
    } else {
        \$id = Request()->param('id');

        if (\$id) \$info = Db::name('{$table}')->where(['id' => \$id])->find();

        \$this->assign('info', \$info);
        \$this->assign('title', (\$id ? '编辑' : '新增') . '{$title}');

        return \$this->view->fetch();
    }
}

AAA;
        }

        return $code;
    }

    /**
     * 生成 列表 HTML代码
     * */
    public function getListHtmlCode()
    {
        $input = Request()->param();

        $action = $input['action'];
        $up_action = ucwords($action);
        $json = json_decode($input['json'], true);

        //新增按钮
        $this->assign('add_btn', '<a href="{:url(do' . $up_action . ')}" class="btn btn-primary btn-lg">新增</a>' . PHP_EOL);

        if ($json) {
            // 筛选HTML
            $screen_html = '';
            // TABLE_TH && TABLE_TD
            $table_th = '';
            $table_td = '';
            // JS
            $js = '';

            foreach ($json as $k => $v) {
                // 筛选HTML
                if ($v['screenField'] === '0') {
                    if (in_array($v['id'], ['text'])) {
                        // 输入框
                        $screen_html .= PHP_EOL . str_replace('SCREEN_LABEL', $v['label'], str_replace('SCREEN_NAME', 'screen_' . $v['name'], $this->view->fetch('/design/tpl/screen_text')));
                    } else if (in_array($v['id'], ['switch', 'select', 'radio'])) {
                        // 下拉框
                        $screen_html .= PHP_EOL . str_replace('SCREEN_LABEL', $v['label'], str_replace('SCREEN_NAME', 'screen_' . $v['name'], $this->view->fetch('/design/tpl/screen_select')));
                    } else {
                        //日期选择
                        $screen_html .= PHP_EOL . str_replace('SCREEN_LABEL', $v['label'], str_replace('SCREEN_NAME', 'screen_' . $v['name'], $this->view->fetch('/design/tpl/screen_date')));

                        $js_render = 'laydate.render({ ' . PHP_EOL . '      elem: ".screen_' . $v['name'] . '"' . PHP_EOL . '   });';
                        $js .= '<script src="__STATIC__/laydate/laydate.js"></script>' . PHP_EOL . '{block name="js"}' . PHP_EOL . '<script>' . PHP_EOL . '    ' . $js_render . PHP_EOL . '</script>' . PHP_EOL . '{/block}';
                    }
                }

                //TABLE_TH && TABLE_TD
                if ($v['fieldShowList'] === '0' && $v['label'] && $v['name']) {
                    $table_th .= PHP_EOL . '                                <th>' . $v['label'] . '</th>';
                    $table_td .= PHP_EOL . '                                <th>{$vo.' . $v['name'] . '}</th>';
                }
            }
        }

        $table_html = str_replace('EDIT_URL', '{:url(do' . $up_action . ', [\'id\' => $vo.id])}', str_replace('TABLE_TD', $table_td, str_replace('TABLE_TH', $table_th, str_replace('tagR', '}', str_replace('tagL', '{', $this->view->fetch('/design/tpl/table'))))));

        $this->assign('screen_html', $screen_html ? $screen_html . PHP_EOL : false);
        $this->assign('table_html', $table_html . PHP_EOL . '                        {$list->render()}' . PHP_EOL);

        $list_html = str_replace('tagR', '}', str_replace('tagL', '{', $this->view->fetch('/design/tpl/list')));

        return $list_html . $js;

    }

    /**
     * 生成 列表 php代码
     * */
    public function getListPhpCode()
    {
        $input = Request()->param();

        $table = $input['table'];
        $action = $input['action'];
        $up_action = ucwords($action);
        $title = $input['title'];
        $json = json_decode($input['json'], true);

        if ($json) {
            // 参数
            $params = '';
            // 筛选条件
            $where = '';
            foreach ($json as $k => $v) {
                // 参数
                if ($v['name'] || $v['startDateName'] || $v['endDateName']) {
                    if ($v['id'] == 'dateRange') {
                        //日期范围
                        $params .= PHP_EOL . '        $' . $v['startDateName'] . ' = $input["' . $v['startDateName'] . '"];' . PHP_EOL . '$' . $v['endDateName'] . ' = $input["' . $v['endDateName'] . '"];';
                    } else {
                        $params .= PHP_EOL . '        $' . $v['name'] . ' = $input["' . $v['name'] . '"];';
                    }
                }

                // 筛选条件
                if ($v['screenField'] === '0') {
                    if (in_array($v['id'], ['text'])) {
                        $where .= PHP_EOL . '        if($' . $v['name'] . ') $where["' . $v['name'] . '"] = "%" . $' . $v['name'] . ' . "%";';
                    } else {
                        $where .= PHP_EOL . '        if($' . $v['name'] . ') $where["' . $v['name'] . '"] = $' . $v['name'] . ';';
                    }
                }
            }
        }

        if ($where) {
            $where = <<<AAA
    \$input = Request()->param();
        {$params}
        {$where}
AAA;
        }

        $is_where = $where ? '->where($where)' : '';

        $code = <<<BBB
/**
 * {$title}列表
 * */
public function {$action}List()
{
    {$where}
    
        \$list = Db::name('{$table}'){$is_where}->paginate();

        \$this->assign('list', \$list);
        \$this->assign('title', '{$title}列表');

        return \$this->view->fetch();
}

/**
 * 删除{$title}
 * */
public function del{$up_action}()
{
        \$id = Request()->param('id');
        
        if (empty(\$id)) adminReturn(2, '{$title}ID缺失');
        
        \$info = Db::name('{$table}')->where(['id' => \$id])->find();
        if (\$info) {
            \$res = Db::name('{$table}')->where(['id' => \$id])->delete();
            if (\$res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
}
BBB;

        return $code;
    }

    public function test()
    {
        $html = $this->view->fetch('/design/componts/form_render');

        $this->assign('html', $html);
        return $this->view->fetch();

    }

}
